<?php

# This controller handles functionality associated with viewing site media
class MediaController extends CustomControllerAction {

	public function init() {
		parent::init();
		$this->_redirector = $this->_helper->getHelper('Redirector');
	}

	public function indexAction() {
		$this->_forward('browse');
	}

	# browseAction: This handles the browsing of site media
	public function browseAction() {

			# Get user, if set
			$user = $this->getRequest()->getParam('user');
			$dates = CommonGenerator::generateCurrentIso8601Dates();

			# Either get a particular user's latest stuff, or get everyone's latest stuff
			if ($user) {

				$usr_sdb_mgr = new UserSDBManager();
				$users = $usr_sdb_mgr->getByFieldValue('username', $user);
				
				if (sizeof($users) > 0)
					$query_str = "['user_id' = '{$users[0]->getId()}'] intersection ['date' > '0']  sort 'date' desc";
				else
					$query_str = "['date' > '0'] sort 'date' desc";
			}
			else {
				$query_str = "['date' > '0'] sort 'date' desc";
			}

			$media_sdb_mgr = new MediaSDBManager();
			$media = $media_sdb_mgr->query($query_str, '5');

			$media_arr = array();
			$desired_thumb_width = "160";
			$thumb_mgr = new ThumbnailManager();
			$comment_sdb_mgr = new CommentSDBManager();

			foreach ($media as $media_obj) 
			{ 
				$comments = $comment_sdb_mgr->getByFieldValue('media_id', $media_obj->getId());
				$current_user = new User();	
				$current_user->load($media_obj->getAttribute('user_id'));

				$stuff = $media_obj->getAttributes();
				$date_key = $media_obj->getAttribute('date');
				$stuff[thumb_url] = $thumb_mgr->getThumbnail($media_obj->getId(), $desired_thumb_width);
				$stuff[username] = $current_user->getAttribute('username');
				$stuff[comments] = sizeof($comments);
				$media_arr[] = $stuff;
			} 
			
			# set up left tabs	
			if ($users[0])
			{
				$left_tabs = array(
					'Media' => array('/media/' . $user),
					'Comments' => array('/comments/' . $user)
				);

				$this->view->badge_title = $users[0]->getAttribute('username') . "'s media";
				
				# check if following this user, and set this
				$this->view->following = null;
			}
			else
			{
				$left_tabs = array(
					'Media' => array('/media'),
					'Comments' => array('/comments')
				);
			}
			
			# set up right tabs
			$auth = Zend_Auth::getInstance();
			if ($auth->hasIdentity())
			{
				$right_tabs = array(
					'Home' => array('/home'),
					'Control Panel' => array('/cpanel')
				);
			}
			else
			{
				$right_tabs = array(
					'Login' => array('/login')
				);
			}
			
			$this->view->tabs = array('selected' => 'Media', 'left_tabs' => $left_tabs, 'right_tabs' => $right_tabs);
			$this->view->media = $media_arr;
	}


	# viewAction: Shows a particular piece of media
	public function viewAction() {

		# Get authorization instance 
		$auth = Zend_Auth::getInstance();

		# Get url
		$url = $this->getRequest()->getParam('url');

		# Get photo details from the database
		$media_obj = new MediaSDBManager();
		$media_obj_result = $media_obj->getByFieldValue('url', $url);
		$photo_id = $media_obj_result[0]->getId();
		$media = $media_obj_result[0]->getAttributes();

		# Insert comment into the datbase, if present
		if ($this->getRequest()->getPost() && $auth->hasIdentity()) {
			$sanitized_comment = strip_tags($this->getRequest()->getPost('comment'));

			$id = $auth->getIdentity()->id;

			# Insert comment into the database
			$comment = new Comment();

			$attributes = array(
											"user_id" => $id,
											"photo_id" => $photo_id,
											"comment" => $sanitized_comment,
											"date" => time()
										);

			$comment->setAttributes($attributes);

			try {
				$comment->save();
			}
			catch(Exception $e) {
				var_dump($e); die();
			}

			try {
				$this->_redirector->gotoURL("/media/view/url/$url");
			}
			catch (Exception $e) {
				var_dump($e); die();
			}
		}
		
		
		# Get thumbnail
		$desired_thumb_width = "320";
		$thumb_mgr = new ThumbnailManager($this->_sdb, $this->_s3, $this->_config, $this->_logger);
		$media[thumb_url] = $thumb_mgr->getThumbnail($photo_id, $desired_thumb_width);
	
		# Get the username associated with this photo
		$user = new User();
		$user->load($media[user_id]);
		$media[username] = $user->getAttribute('username');
		
		# Send the media array to the view
		$this->view->media = $media;

		# Get comments for this piece of media
		$comment_obj = new CommentSDBManager();
		$comment_obj_result = $comment_obj->query("['photo_id' = '$photo_id'] intersection ['date' > '0'] sort 'date'");
		
		# Construct an array of comments to hand off to smarty
		$comments = array();

		foreach($comment_obj_result as $comment) {
			$user->clearObject();
			$user->load($comment->getAttribute('user_id'));
			$attributes = $comment->getAttributes();
			$attributes['username'] = $user->getAttribute('username');

			$comments[] = $attributes; 
		}

		$this->view->comments = $comments;

		# Let smarty know if this person is logged in (and who they may be)
		$this->view->is_authorized = $auth->hasIdentity();
		$this->view->logged_in_username = $auth->getIdentity->username;
	}


	# CommentsAction: Shows only the comments for a particular media piece
	public function commentsAction() {
	
		# Get the photo's url
		$url = $this->getRequest()->getParam('url');

		# Get the photo's id
		$media_obj = new MediaSDBManager();
		$media = $media_obj->getByFieldValue('url', $url);
		$photo_id = $media[0]->getId();

		$photo_title = $media[0]->getAttribute('title');
		
		# Get comments for this media piece
		$comment_obj = new CommentSDBManager();
		$media_comments = $comment_obj->query("['photo_id' = '$photo_id'] intersection ['date' > '0'] sort 'date' asc");

		foreach($media_comments as $comment) {
			$comment_id = $comment->getId();
			$comments[$comment_id] = $comment->getAttributes();

			# Get commenter's username
			$user_obj = new User();
			$user_obj->load($comment->getAttribute('user_id'));
			$comments[$comment_id]['username'] = $user_obj->getAttribute('username');
		}
	
		# Send comments to the view
		$this->view->comments = $comments;

		# Send photo's title to the view
		$this->view->photo_title = $photo_title;
	}
}
